import 'dart:ui';

import 'package:animated_transitions/animated_transitions.dart';
import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter_redux/flutter_redux.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:gradient_borders/gradient_borders.dart';
import '../../core/index.dart';
import '../../core/widgets/report_dialog.dart';
import 'video_call_page.dart';

/// 私人聊天界面 - 与特定用户的对话
class VamosPrivateChatInterface extends StatefulWidget {
  final UserDataEntity targetUser;
  final String? conversationId; // 可选的现有对话ID

  const VamosPrivateChatInterface({
    super.key,
    required this.targetUser,
    this.conversationId,
  });

  @override
  State<VamosPrivateChatInterface> createState() =>
      _VamosPrivateChatInterfaceState();
}

class _VamosPrivateChatInterfaceState extends State<VamosPrivateChatInterface> {
  final TextEditingController _messageController = TextEditingController();
  String? _currentConversationId;
  bool _isLoading = false;

  @override
  void initState() {
    super.initState();
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    if (_currentConversationId == null && !_isLoading) {
      // 使用 WidgetsBinding.instance.addPostFrameCallback 确保在 build 完成后执行
      WidgetsBinding.instance.addPostFrameCallback((_) {
        if (mounted) {
          _initializeConversation();
        }
      });
    }
  }

  @override
  void dispose() {
    _messageController.dispose();
    super.dispose();
  }

  /// 初始化对话
  void _initializeConversation() async {
    if (!mounted) return;

    setState(() {
      _isLoading = true;
    });

    try {
      final store = StoreProvider.of<AppState>(context);
      final currentUser = store.state.userState.activeUser;

      if (currentUser == null) {
        if (mounted) {
          Navigator.of(context).pop();
        }
        return;
      }

      final chatManager = serviceLocator<ReduxChatManager>();

      // 如果提供了对话ID，直接使用
      if (widget.conversationId != null) {
        _currentConversationId = widget.conversationId;
        chatManager.setActiveConversation(widget.conversationId!);
      } else {
        // 检查是否已存在与目标用户的对话
        final existingConversation = _findExistingConversation(
          chatManager.getAllConversations(),
          currentUser.uniqueId,
          widget.targetUser.uniqueId,
        );

        if (existingConversation != null) {
          _currentConversationId = existingConversation.conversationId;
          chatManager.setActiveConversation(
            existingConversation.conversationId,
          );
        } else {
          // 创建新对话
          final newConversation = ChatConversationEntity(
            conversationId: 'conv_${DateTime.now().millisecondsSinceEpoch}',
            participantId: widget.targetUser.uniqueId,
            participantName: widget.targetUser.displayName,
            participantAvatar:
                widget.targetUser.profileImage.isNotEmpty
                    ? widget.targetUser.profileImage
                    : 'assets/images/default_avatar.png',
            lastMessageContent: '',
            lastMessageType: ChatMessageType.textMessage,
            lastMessageTime: DateTime.now(),
            messageList: [],
          );

          final success = await chatManager.createNewConversation(
            newConversation,
          );
          if (success) {
            _currentConversationId = newConversation.conversationId;
            chatManager.setActiveConversation(newConversation.conversationId);
          } else {
            if (mounted) {
              NotificationUtils.showError(
                context,
                message: 'Failed to create conversation',
              );
              Navigator.of(context).pop();
            }
            return;
          }
        }
      }
    } catch (e) {
      if (mounted) {
        NotificationUtils.showError(
          context,
          message: 'Error initializing chat: $e',
        );
        Navigator.of(context).pop();
      }
      return;
    } finally {
      if (mounted) {
        setState(() {
          _isLoading = false;
        });
      }
    }
  }

  /// 查找现有对话
  ChatConversationEntity? _findExistingConversation(
    List<ChatConversationEntity> conversations,
    String currentUserId,
    String targetUserId,
  ) {
    for (final conversation in conversations) {
      // 检查是否是与目标用户的对话
      if (conversation.participantId == targetUserId) {
        return conversation;
      }
    }
    return null;
  }

  @override
  Widget build(BuildContext context) {
    return StoreConnector<AppState, AppState>(
      converter: (store) => store.state,
      builder: (context, state) {
        final currentUser = state.userState.activeUser;

        if (currentUser == null) {
          return Scaffold(
            body: Center(
              child: Text(
                'Please login to access chat',
                style: TextStyle(color: Colors.white, fontSize: 18.sp),
              ),
            ),
          );
        }

        return Scaffold(
          body: Container(
            width: double.infinity,
            height: double.infinity,
            decoration: const BoxDecoration(
              image: DecorationImage(
                image: AssetImage('assets/images/my_background.png'),
                fit: BoxFit.cover,
              ),
            ),
            child:
                _isLoading
                    ? _buildLoadingState()
                    : _buildChatContent(state, currentUser),
          ).safeArea(top: false, bottom: false),
        );
      },
    );
  }

  Widget _buildLoadingState() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          CircularProgressIndicator(
            valueColor: AlwaysStoppedAnimation<Color>(Color(0xFF83BE4A)),
          ),
          SizedBox(height: 16.h),
          Text(
            'Initializing chat...',
            style: TextStyle(color: Colors.white, fontSize: 16.sp),
          ),
        ],
      ),
    );
  }

  Widget _buildChatContent(AppState state, UserDataEntity currentUser) {
    return Column(
      children: [
        // 顶部导航栏
        _buildTopNavigationBar(),

        // 聊天头部
        _buildChatHeader(),

        // 消息列表
        Expanded(child: _buildMessagesList(state, currentUser)),

        // 输入框
        _buildMessageInput(),
      ],
    );
  }

  /// 构建顶部导航栏
  Widget _buildTopNavigationBar() {
    return Container(
      padding: EdgeInsets.only(
        top: MediaQuery.of(context).padding.top + 12.h,
        left: 16.w,
        right: 16.w,
        bottom: 12.h,
      ),
      child: Row(
        children: [
          // 返回按钮
          Container(
            width: 40.w,
            height: 40.w,
            decoration: BoxDecoration(
              color: Colors.black.withOpacity(0.3),
              shape: BoxShape.circle,
            ),
            child: Icon(
              Icons.arrow_back,
              size: 26.w,
              color: Colors.white,
            ).center().inkWell(
              onTap: () {
                Navigator.of(context).pop();
              },
            ),
          ),

          SizedBox(width: 16.w),

          // 标题
          Expanded(
            child: Text(
              'Chat',
              style: TextStyle(
                color: Colors.white,
                fontSize: 20.sp,
                fontWeight: FontWeight.w700,
                fontFamily:
                    GoogleFonts.poppins(fontWeight: FontWeight.w700).fontFamily,
              ),
            ),
          ),

          // 举报按钮
          Container(
            width: 40.w,
            height: 40.w,
            decoration: BoxDecoration(
              color: Colors.black.withOpacity(0.3),
              shape: BoxShape.circle,
            ),
            child: Image.asset(
              'assets/images/report.png',
              width: 24.w,
              height: 24.w,
            ).center().inkWell(
              onTap: () {
                _showReportDialog();
              },
            ),
          ),
        ],
      ),
    );
  }

  /// 构建聊天头部
  Widget _buildChatHeader() {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 16.w, vertical: 8.h),
      padding: EdgeInsets.all(16.w),
      decoration: BoxDecoration(
        color: Colors.white.withOpacity(0.1),
        borderRadius: BorderRadius.circular(16.r),
        border: Border.all(color: Colors.white.withOpacity(0.2), width: 1),
      ),
      child: Row(
        children: [
          // 用户头像
          Container(
            width: 50.w,
            height: 50.w,
            decoration: BoxDecoration(
              shape: BoxShape.circle,
              border: GradientBoxBorder(
                width: 2.w,
                gradient: LinearGradient(
                  colors: [
                    Color(0xFF83BE4A),
                    Color(0xFFFB894E),
                    Color(0xFFE91E63),
                  ],
                ),
              ),
            ),
            child: Container(
              width: 46.w,
              height: 46.w,
              margin: EdgeInsets.all(2.w),
              decoration: BoxDecoration(
                shape: BoxShape.circle,
                color: Colors.transparent,
              ),
              child: ClipOval(
                child:
                    widget.targetUser.profileImage.isNotEmpty
                        ? Image.asset(
                          widget.targetUser.profileImage,
                          width: 42.w,
                          height: 42.w,
                          fit: BoxFit.cover,
                        )
                        : Icon(
                          Icons.person,
                          size: 24.w,
                          color: Colors.white,
                        ).center(),
              ),
            ),
          ),

          SizedBox(width: 12.w),

          // 用户信息
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  widget.targetUser.displayName,
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 18.sp,
                    fontWeight: FontWeight.w600,
                    fontFamily:
                        GoogleFonts.poppins(
                          fontWeight: FontWeight.w600,
                        ).fontFamily,
                  ),
                ),
                SizedBox(height: 4.h),
                Text(
                  widget.targetUser.personalBio.isNotEmpty
                      ? widget.targetUser.personalBio
                      : 'Online',
                  style: TextStyle(
                    color: Colors.white.withOpacity(0.7),
                    fontSize: 14.sp,
                    fontFamily:
                        GoogleFonts.poppins(
                          fontWeight: FontWeight.w400,
                        ).fontFamily,
                  ),
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                ),
              ],
            ),
          ),

          // 视频通话按钮
          Container(
            width: 40.w,
            height: 40.w,
            decoration: BoxDecoration(
              color: Colors.white.withOpacity(0.2),
              shape: BoxShape.circle,
            ),
            child: Image.asset(
              'assets/images/call.png',
              width: 24.w,
              height: 24.w,
            ).center().inkWell(
              onTap: () {
                _startVideoCall();
              },
            ),
          ),
        ],
      ),
    );
  }

  /// 构建消息列表
  Widget _buildMessagesList(AppState state, UserDataEntity currentUser) {
    if (_currentConversationId == null) {
      return Center(
        child: Text(
          'Loading conversation...',
          style: TextStyle(
            color: Colors.white.withOpacity(0.7),
            fontSize: 16.sp,
          ),
        ),
      );
    }

    final conversation = state.chatState.conversationCollection.firstWhere(
      (conv) => conv.conversationId == _currentConversationId,
      orElse:
          () => ChatConversationEntity(
            conversationId: '',
            participantId: '',
            participantName: '',
            participantAvatar: '',
            lastMessageContent: '',
            lastMessageType: ChatMessageType.textMessage,
            lastMessageTime: DateTime.now(),
            messageList: [],
          ),
    );

    final messages = conversation.messageList;

    return Container(
      margin: EdgeInsets.symmetric(horizontal: 16.w),
      decoration: BoxDecoration(
        color: Colors.white.withOpacity(0.1),
        borderRadius: BorderRadius.circular(16.r),
        border: Border.all(color: Colors.white.withOpacity(0.2), width: 1),
      ),
      child:
          messages.isEmpty
              ? _buildEmptyState()
              : ListView.builder(
                padding: EdgeInsets.symmetric(vertical: 16.h, horizontal: 8.w),
                itemCount: messages.length,
                itemBuilder: (context, index) {
                  final message = messages[index];
                  final isCurrentUser =
                      message.senderId == currentUser.uniqueId;

                  return Padding(
                    padding: EdgeInsets.only(bottom: 12.h),
                    child: _buildMessageBubble(message, isCurrentUser),
                  );
                },
              ),
    );
  }

  /// 构建空状态
  Widget _buildEmptyState() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Image.asset(
            'assets/images/no_data.png',
            width: 80.w,
            height: 80.w,
            fit: BoxFit.contain,
          ),
          SizedBox(height: 16.h),
          Text(
            'No messages yet',
            style: TextStyle(
              color: Colors.white.withOpacity(0.7),
              fontSize: 16.sp,
              fontWeight: FontWeight.w500,
            ),
          ),
          SizedBox(height: 8.h),
          Text(
            'Start a conversation with ${widget.targetUser.displayName}',
            style: TextStyle(
              color: Colors.white.withOpacity(0.5),
              fontSize: 14.sp,
            ),
            textAlign: TextAlign.center,
          ),
        ],
      ),
    );
  }

  /// 构建消息气泡
  Widget _buildMessageBubble(ChatMessageEntity message, bool isCurrentUser) {
    if (message.messageType == ChatMessageType.callFailedMessage) {
      return _buildCallFailedMessage();
    }

    return Row(
      mainAxisAlignment:
          isCurrentUser ? MainAxisAlignment.end : MainAxisAlignment.start,
      children: [
        Container(
          constraints: BoxConstraints(
            maxWidth: MediaQuery.of(context).size.width * 0.7,
          ),
          padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
          decoration: BoxDecoration(
            color: isCurrentUser ? Colors.white : const Color(0xFF83BE4A),
            borderRadius:
                isCurrentUser
                    ? BorderRadius.only(
                      topLeft: Radius.circular(16.r),
                      topRight: Radius.circular(16.r),
                      bottomLeft: Radius.circular(16.r),
                      bottomRight: Radius.circular(4.r),
                    )
                    : BorderRadius.only(
                      topLeft: Radius.circular(16.r),
                      topRight: Radius.circular(16.r),
                      bottomLeft: Radius.circular(4.r),
                      bottomRight: Radius.circular(16.r),
                    ),
            border:
                isCurrentUser
                    ? Border.all(color: Colors.grey.withOpacity(0.3), width: 1)
                    : null,
          ),
          child: Text(
            message.content,
            style: TextStyle(
              color: isCurrentUser ? Colors.black : Colors.white,
              fontSize: 14.sp,
              fontFamily:
                  GoogleFonts.poppins(fontWeight: FontWeight.w400).fontFamily,
            ),
          ),
        ),
      ],
    );
  }

  /// 构建通话失败消息
  Widget _buildCallFailedMessage() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Container(
          padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 8.h),
          decoration: BoxDecoration(
            color: Colors.red.withOpacity(0.1),
            borderRadius: BorderRadius.circular(16.r),
            border: Border.all(color: Colors.red.withOpacity(0.3), width: 1),
          ),
          child: Row(
            mainAxisSize: MainAxisSize.min,
            children: [
              Icon(Icons.call_end, color: Colors.red, size: 16.w),
              SizedBox(width: 8.w),
              Text(
                'Call failed',
                style: TextStyle(
                  color: Colors.red,
                  fontSize: 12.sp,
                  fontWeight: FontWeight.w500,
                ),
              ),
            ],
          ),
        ),
      ],
    );
  }

  /// 构建消息输入框
  Widget _buildMessageInput() {
    return Container(
      margin: EdgeInsets.all(16.w),
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 8.h),
      decoration: BoxDecoration(
        color: Colors.white.withOpacity(0.1),
        borderRadius: BorderRadius.circular(24.r),
        border: Border.all(color: Colors.white.withOpacity(0.2), width: 1),
      ),
      child: Row(
        children: [
          // 输入框
          Expanded(
            child: TextField(
              controller: _messageController,
              style: TextStyle(
                color: Colors.white,
                fontSize: 16.sp,
                fontFamily:
                    GoogleFonts.poppins(fontWeight: FontWeight.w400).fontFamily,
              ),
              decoration: InputDecoration(
                hintText: 'Type a message...',
                hintStyle: TextStyle(
                  color: Colors.white.withOpacity(0.5),
                  fontSize: 16.sp,
                  fontFamily:
                      GoogleFonts.poppins(
                        fontWeight: FontWeight.w400,
                      ).fontFamily,
                ),
                border: InputBorder.none,
                contentPadding: EdgeInsets.symmetric(vertical: 8.h),
                isDense: true,
              ),
              maxLines: null,
              onSubmitted: (text) {
                if (text.trim().isNotEmpty) {
                  _sendMessage(text.trim());
                }
              },
            ),
          ),

          SizedBox(width: 8.w),

          // 发送按钮
          Container(
            width: 40.w,
            height: 40.w,
            decoration: BoxDecoration(
              color: const Color(0xFF83BE4A),
              shape: BoxShape.circle,
            ),
            child: Icon(
              Icons.send,
              color: Colors.white,
              size: 20.w,
            ).center().inkWell(
              onTap: () {
                final text = _messageController.text.trim();
                if (text.isNotEmpty) {
                  _sendMessage(text);
                }
              },
            ),
          ),
        ],
      ),
    );
  }

  /// 发送消息
  void _sendMessage(String content) async {
    if (_currentConversationId == null) return;

    final store = StoreProvider.of<AppState>(context);
    final currentUser = store.state.userState.activeUser;

    if (currentUser == null) return;

    final chatManager = serviceLocator<ReduxChatManager>();

    final success = await chatManager.sendTextMessage(
      conversationId: _currentConversationId!,
      senderId: currentUser.uniqueId,
      receiverId: widget.targetUser.uniqueId,
      content: content,
    );

    if (success) {
      _messageController.clear();
    } else {
      if (mounted) {
        NotificationUtils.showError(context, message: 'Failed to send message');
      }
    }
  }

  /// 开始视频通话
  void _startVideoCall() {
    if (_currentConversationId == null) return;

    Navigator.of(context).push(
      TransitionPageRoute(
        builder:
            (context) => VamosVideoCallInterface(
              conversationId: _currentConversationId!,
            ),
        transitionAnimation: GrowingBarsTransition(
          colors: [Color(0xFF83BE4A), Color(0xFFF3E3C6), Color(0xFFFB894E)],
        ),
      ),
    );
  }

  /// 显示举报对话框
  void _showReportDialog() {
    showVamosReportDialog(
      context: context,
      title: 'Report User',
      subtitle:
          'Please select a reason for reporting ${widget.targetUser.displayName}.',
      onReportSubmitted: (option) {
        _handleReportSubmission(option);
      },
    );
  }

  /// 处理举报提交
  void _handleReportSubmission(VamosReportOption option) {
    // 删除与这个用户的所有消息
    if (_currentConversationId != null) {
      final chatManager = serviceLocator<ReduxChatManager>();
      chatManager.clearConversationMessages(_currentConversationId!);
    }

    // 显示举报成功提示
    NotificationUtils.showSuccess(
      context,
      message: 'Report submitted successfully',
    );

    // 返回上一个页面
    if (mounted) {
      Navigator.of(context).pop();
    }
  }
}
